<template>
  <div class="homeFreshGoods">

    <homePannel ref="target" title="新鲜好物" sub-title="新鲜出炉">
      <!-- 作用域插槽 -->
      <template #right>
        <!-- 发现更多链接组件 -->
        <XtxMore path="/"></XtxMore>
      </template>
      <ul class="goodsList" v-if="freshGoodsList.length>0">
        <li v-for="item in freshGoodsList" :key="item.id">
          <!--  -->
          <RouterLink :to="`/goods/${item.id}`">
          <!-- 图片懒加载 -->
            <img v-imgLazy="item.picture" alt="">
            <p class="name ellipsis">{{item.name}}</p>
            <p class="price">&yen;{{item.price}}</p>
          </RouterLink>
        </li>
      </ul>
      <!-- 组件数据开始前显示骨架屏 -->
      <template v-else>
          <ul class="goodsList" v-if="freshGoodsList.length>0">
        <li v-for="i in 4" :key="i">
          <!-- 骨架屏组件 -->
          <XtxSkeleton :width="300" :height="406" bg="rgba(255,255,255,.2)" style="margin-right:5px"></XtxSkeleton>
         <XtxSkeleton :width="300" :height="406" bg="rgba(255,255,255,.2)" style="margin-right:5px"></XtxSkeleton>
          <XtxSkeleton :width="300" :height="406" bg="rgba(255,255,255,.2)" style="margin-right:5px"></XtxSkeleton>
        </li>
      </ul>
      </template>
    </homePannel>
  </div>
</template>

<script>
import { ref } from 'vue'
import homePannel from './homePannel.vue'
import { freshGoods } from '@/api/home/index.js'
import { useIntersectionObserver } from '@vueuse/core'
export default {
  name: 'homeFreshGoods',
  components: { homePannel },
  setup () {
    // 初始化懒加载监视对象
    const target = ref(null)
    // 存储商品信息的数组
    const freshGoodsList = ref([])
    const { stop } = useIntersectionObserver(
      target,
      ([{ isIntersecting }], observerElement) => {
        //  业务逻辑
        // 如果进入监视区
        if (isIntersecting) {
          // 停止观察
          stop()
          // 马上加载相应数据
          // 调用请求好物的接口
          freshGoods().then(data => {
            // 请求得到的数据验证后赋值给初始数组
            console.log(data, '新鲜好物数据')
            freshGoodsList.value = data.result
          })
        }
      }, // 表示进入区域的面积为多少时执行停止观察，请求数据的逻辑
      { threshold: 0.6 }
    )

    // // 调用请求好物的接口
    // freshGoods().then((data) => {
    //   // 请求得到的数据验证后赋值给初始数组
    //   console.log(data, '新鲜好物数据')
    //   freshGoodsList.value = data.result
    // })
    return {
      freshGoodsList,
      target
    }
  }
}
</script>

<style lang="less" scoped>
.homeFreshGoods {
  margin-top: 20px;
}
.goodsList {
  display: flex;
  justify-content: space-between;
  height: 406px;
  // width: 1240px;
  li {
    width: 300px;
    height: 406px;
    background-color: #f0f9f4;
    .hoverShadow();
    img {
      width: 306px;
      height: 306px;
    }
    p {
      font-size: 22px;
      padding: 12px 30px 0px;
      text-align: center;
    }
    .price {
      padding: 12px 30px 0;
      color: #cf4444;
    }
  }
}
</style>
